package com.wxzz.elearing.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wxzz.elearing.pay.amqp.producer.PayMessageProducer;
import com.wxzz.elearing.pay.dto.UserBankCardDto;
import com.wxzz.elearing.pay.entity.UserBankCard;
import com.wxzz.elearing.pay.mapper.UserBankCardMapper;
import com.wxzz.elearing.pay.service.IUserBankCardService;
import com.wxzz.elearning.common.aop.Idempotent;
import com.wxzz.elearning.common.bean.SmsConfig;
import com.wxzz.elearning.common.constants.RedisConstants;
import com.wxzz.elearning.common.dto.SystemMessageMqDto;
import com.wxzz.elearning.common.exception.ServiceException;
import com.wxzz.elearning.common.utils.BankUtil;
import com.wxzz.elearning.common.vo.JgPageVo;
import com.wxzz.elearning.common.vo.ReturnVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author
 * @since 2021-04-23
 */
@Service
public class UserBankCardServiceImpl extends ServiceImpl<UserBankCardMapper, UserBankCard> implements IUserBankCardService {

    @Autowired
    private UserBankCardMapper userBankCardMapper;

    @Idempotent
    @Transactional
    @Override
    public ReturnVO saveUserBankCard(JSONObject jsonObject, UserBankCard userBankCard) {
        if (userBankCard.getUserType() == null) {
            throw new ServiceException("请传入用户类型");
        }
        if (StringUtils.isBlank(userBankCard.getPersonName())) {
            throw new ServiceException("请传入持卡人");
        }
        if (StringUtils.isBlank(userBankCard.getBankCardNum())) {
            throw new ServiceException("请输入银行卡号");
        }
        Long userId = null;
        //查询用户对应id
        if (userBankCard.getUserType() == 0) {
            //平台
            userId = 0L;
        }
        if (userBankCard.getUserType() == 1) {
            //管理端
            userId = jsonObject.getLong("enterpriseId");
        }
        if (userBankCard.getUserType() == 2) {
            //客户端
            userId = jsonObject.getLong("id");
        }
        if (userBankCard.getUserType() == 3) {
            //讲师端
            userId = jsonObject.getLong("docentId");
        }
        userBankCard.setUserId(userId);
        //查询银行名称
        String[] res = BankUtil.bankMsg(userBankCard.getBankCardNum());
        if (StringUtils.isBlank(res[0])) {
            throw new ServiceException("请输入正确的银行卡号");
        }
        userBankCard.setBankName(res[0]);
        userBankCard.setBankIcon(res[1]);
        if (userBankCard.getIsDefault() != null && userBankCard.getIsDefault() == 1) {
            List<UserBankCard> userBankCards = userBankCardMapper.selectList(new LambdaQueryWrapper<UserBankCard>()
                    .eq(UserBankCard::getIsDefault, 1)
                    .eq(UserBankCard::getUserId, userId)
                    .eq(UserBankCard::getUserType, userBankCard.getUserType()));
            for (UserBankCard bankCard : userBankCards) {
                bankCard.setIsDefault(0);
                userBankCardMapper.updateById(bankCard);
            }
        }
        if (userBankCard.getId() == null) {
            userBankCardMapper.insert(userBankCard);
        } else {
            userBankCardMapper.updateById(userBankCard);
        }
        return new ReturnVO("添加或修改银行卡成功", userBankCard.getId());
    }

    @Override
    public ReturnVO<JgPageVo<List<UserBankCard>>> listUserBankCardByUser(JSONObject jsonObject, UserBankCardDto userBankCardDto) {
        if (userBankCardDto.getUserType() == null) {
            throw new ServiceException("请传入用户类型");
        }
        Long userId = null;
        //查询用户对应id
        if (userBankCardDto.getUserType() == 0) {
            //平台
            userId = 0L;
        }
        if (userBankCardDto.getUserType() == 1) {
            //管理端
            userId = jsonObject.getLong("enterpriseId");
        }
        if (userBankCardDto.getUserType() == 2) {
            //客户端
            userId = jsonObject.getLong("id");
        }
        if (userBankCardDto.getUserType() == 3) {
            //讲师端
            userId = jsonObject.getLong("docentId");
        }
        PageHelper.startPage(userBankCardDto.getCurPage(), userBankCardDto.getMaxPage());
        List<UserBankCard> userBankCards = userBankCardMapper.selectList(new LambdaQueryWrapper<UserBankCard>()
                .eq(UserBankCard::getUserType, userBankCardDto.getUserType())
                .eq(UserBankCard::getUserId, userId)
                .orderByDesc(UserBankCard::getCreateTime));
        return new ReturnVO("列出我的银行卡", new JgPageVo<>(new PageInfo(userBankCards)));
    }

    @Override
    public ReturnVO deleteUserBankCardById(Long userBankCardId) {
        userBankCardMapper.deleteById(userBankCardId);
        return new ReturnVO("删除银行卡", userBankCardId);
    }

    @Override
    public ReturnVO<UserBankCard> selectDefault(JSONObject jsonObject, Integer userType) {
        Long userId = null;
        //查询用户对应id
        if (userType == 0) {
            //平台
            userId = 0L;
        }
        if (userType == 1) {
            //管理端
            userId = jsonObject.getLong("enterpriseId");
        }
        if (userType == 2) {
            //客户端
            userId = jsonObject.getLong("id");
        }
        if (userType == 3) {
            //讲师端
            userId = jsonObject.getLong("docentId");
        }
        List<UserBankCard> userBankCards = userBankCardMapper.selectList(new LambdaQueryWrapper<UserBankCard>()
                .eq(UserBankCard::getUserType, userType)
                .eq(UserBankCard::getUserId, userId)
                .eq(UserBankCard::getIsDefault, 1));
        if (userBankCards.size() == 0) {
            return new ReturnVO<>("我的默认银行卡查询成功", null);
        }
        return new ReturnVO<>("我的默认银行卡查询成功", userBankCards.get(0));
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ReturnVO sendUpdateBankCardCode(String phone) {
        if (StringUtils.isBlank(phone)) {
            throw new ServiceException("该账号没有手机号,请先设置手机号");
        }
        //发送验证码
        int intFlag = (int) (Math.random() * 1000000);
        String flag = String.valueOf(intFlag);
        if (flag.length() == 6 && flag.substring(0, 1).equals("9")) {
        } else {
            intFlag = intFlag + 100000;
        }
        redisTemplate.opsForValue().set(RedisConstants.PHONE_CODE + phone, String.valueOf(intFlag));
        SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
        //验证码类短信
        systemMessageMqDto.setSmsType(1);
        systemMessageMqDto.setPhones(
                new ArrayList<String>() {
                    {
                        add(phone);
                    }
                }
        );
        systemMessageMqDto.setTemplateId(SmsConfig.updateBankCardId);
        int finalIntFlag = intFlag;//匿名内部类语法规则
        systemMessageMqDto.setParams(new ArrayList<String>() {
            {
                add(String.valueOf(finalIntFlag));
            }
        });
        payMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
        return new ReturnVO<>("验证码发送成功", null);
    }

    @Override
    public ReturnVO verifyCode(String phone, String code) {
        String redisCode = redisTemplate.opsForValue().get(RedisConstants.PHONE_CODE + phone);
        if (StringUtils.isBlank(code)) {
            throw new ServiceException("验证码失效");
        }
        if (!code.equals(redisCode)) {
            throw new ServiceException("验证码错误");
        }
        return new ReturnVO<>("验证成功", null);
    }

    @Autowired
    private PayMessageProducer payMessageProducer;
}
